﻿using Barcode_Project.Entity;
using Barcode_Project.Local;
using Barcode_Project.Network;
using DevExpress.Internal;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RJCP.IO.Ports;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.WebRequestMethods;

namespace Barcode_Project.MatAuxRePrint
{
    public partial class StuffRePrint : DevExpress.XtraEditors.XtraForm
    {
        HttpAgreement http;
        ILog _log;
        Dictionary<string, string> datas;
        public StuffRePrint(Dictionary<string, string> pars)
        {
            _log = LogManager.GetLogger(GetType().Name);
            http = new HttpAgreement();
            datas = pars;

            InitializeComponent();

            new ComputerTask().LoadPrinter(select_printer);
            new ComputerTask().LoadTemplate(select_template);

            OpenPort();
        }

        SerialPortStream _port;
        void OpenPort()
        {
            var comName = ConfigurationManager.AppSettings["COM"].ToString();
            var baudRate = ConfigurationManager.AppSettings["baud rate"].ToString();

            if (_port == null)
            {
                _port = new SerialPortStream(comName, int.Parse(baudRate));
                _port.DataReceived += _port_DataReceived;
            }

            if (_port == null && !(_port.IsOpen))
            {
                try
                {
                    _port.Open();
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(ex.Message);
                }
            }
        }

        private void _port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                this.Invoke(new Action(() =>
                {
                    led_weight.Value = _port.ReadExisting();
                }));
            }
            catch (Exception ex)
            {

            }
        }

        private void lookUp_old_AutoSuggest(object sender, DevExpress.XtraEditors.Controls.LookUpEditAutoSuggestEventArgs e)
        {
            e.QuerySuggestions = new RemoteRequest().BarCodeAutoSuggest(e.Text, e.CancellationToken);
        }

        private void lookUp_old_EditValueChanged(object sender, EventArgs e)
        {
            if (input_old.EditValue != null && input_old.EditValue.ToString().Length >= 12)
            {
                LoadOldData();
            }
        }

        void LoadOldData()
        {
            var codeStr = input_old.EditValue.ToString();

            var barCodeDic = new Dictionary<string, string>();
            barCodeDic["barCode"] = codeStr;

            var returnDic = new Dictionary<string, string>();

            string url = CommonMethods.APIUrl() + "GetOldBarCodeInfo";
            var info = http.HttpPost(url, JsonConvert.SerializeObject(barCodeDic));

            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var obj = JsonConvert.DeserializeObject<JObject>(info);
            if (bool.Parse(obj["result"].ToString()))
            {
                returnDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(obj["data"].ToString());
            }

            CommonMethods.SetFormValue(group_data.Controls, returnDic, "input_");

            //var barCode = new RemoteRequest()
            //.GetOldBarCodeInfo(lookUp_old.EditValue.ToString());

            //if (barCode.barCode != null)
            //{
            //    input_proCode.EditValue = barCode.proCode;
            //    input_proName.EditValue = barCode.proName;
            //    input_number.EditValue = barCode.number;
            //    input_spec.EditValue = barCode.spec;
            //}
        }

        private void button_rePrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!CheckBeforePrint())
            {
                return;
            }

            var json = CollectData();

            string url = CommonMethods.APIUrl() + "MatAuxRePrint";
            var info = http.HttpPost(url, json);

            if (string.IsNullOrWhiteSpace(info))
            {
                XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var obj = JsonConvert.DeserializeObject<JObject>(info);

            if (bool.Parse(obj["result"].ToString()))
            {
                //var table = CommonMethods.CreatePrintTableByDictionary(datas, obj["data"].ToString());

                var table = new RemoteRequest().GetReBarInfo(datas["oldBarCode"].ToString());
                table.Rows[0]["barCode"]= obj["data"].ToString().Split(',')[0];

                var printerName = ((ItemSelector)select_printer.GetSelectedDataRow()).code;
                var templatePath = ((ItemSelector)select_template.GetSelectedDataRow()).code;//模板路径

                new ComputerTask().StartPrintingTask(table, printerName, templatePath);

                input_old.EditValue = "";
            }
            else
            {
                XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //var dt = new RemoteRequest().MatAuxRePrint(json);

            //if (dt == null)
            //{
            //    return;
            //}

            //var printerName = ((ItemSelector)select_printer.GetSelectedDataRow()).code;
            //var templatePath = ((ItemSelector)select_template.GetSelectedDataRow()).code;

            //var result = new ComputerTask().StartPrintingTask(dt, printerName, templatePath);

            //if (result)
            //{
            //    var args = new XtraMessageBoxArgs();
            //    args.AutoCloseOptions.ShowTimerOnDefaultButton = true;
            //    args.DefaultButtonIndex = 0;
            //    args.AutoCloseOptions.Delay = 2000;
            //    args.Caption = "提示";
            //    args.Text = "打印任务发送成功";

            //    XtraMessageBox.Show(args);
            //}
        }

        // 打印之前，检查必填项
        bool CheckBeforePrint()
        {
            var result = false;

            if (input_old.EditValue == null)
            {
                XtraMessageBox.Show("请填写条码");
                return result;
            }

            if (string.IsNullOrEmpty(input_old.EditValue.ToString()))
            {
                XtraMessageBox.Show("请填写条码");
                return result;
            }

            if (select_printer.GetSelectedDataRow() == null)
            {
                XtraMessageBox.Show("请选择打印机");
                return result;
            }
            if (select_template.GetSelectedDataRow() == null)
            {
                XtraMessageBox.Show("请选择打印模板");
                return result;
            }

            result = true;
            return result;
        }

        // 组织数据
        string CollectData()
        {
            datas["oldBarCode"] = input_old.EditValue.ToString();
            datas["newMeter"] = input_remainMeter.EditValue.ToString();
            datas["newWeight"] = led_weight.Value;

            if (cb_check.EditValue.ToString() == "是")
            {
                datas["isCheck"] = "1";
            }
            else
            {
                datas["isCheck"] = "0";
            }

            return JsonConvert.SerializeObject(datas);
        }

        private void button_exit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Application.Exit();
        }

        private void input_manual_EditValueChanged(object sender, EventArgs e)
        {
            led_weight.Value = input_manual.EditValue.ToString();
        }

        private void btn_update_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var r = XtraMessageBox.Show("即将关闭程序进行升级，是否继续？", "提示", MessageBoxButtons.OKCancel);
            if (r == DialogResult.OK)
            {
                new RemoteRequest().UpdateCmdProgram();
            }
        }

        private void StuffRePrint_Load(object sender, EventArgs e)
        {
            SetCheckValue();
        }

        void SetCheckValue()
        {
            cb_check.Properties.Items.AddRange(new object[]
            {
                "是","否"
            });

            //// 如果是复合工序，默认为是
            //if (datas["gxCode"] == "FH")
            //{
            cb_check.SelectedIndex = 1;
            //}
            //else
            //{
            //    cb_check.SelectedIndex = 1;
            //}
        }
    }
}